package top.mh.mybatis.executor;

import top.mh.mybatis.config.BoundSql;
import top.mh.mybatis.pojo.Configuration;
import top.mh.mybatis.pojo.MappedStatement;
import top.mh.mybatis.utils.GenericTokenParser;
import top.mh.mybatis.utils.ParameterMapping;
import top.mh.mybatis.utils.ParameterMappingTokenHandler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author mh
 * @version 1.0
 * @description
 * @since 2024/2/2 16:26
 */
public class SimpleExecutor implements Executor {

    private Connection connection;
    private PreparedStatement preparedStatement;
    private ResultSet resultSet;

    @Override
    public <T> List<T> query(Configuration configuration, MappedStatement mappedStatement, Object param) throws Exception {
        // 1.加载驱动，获取数据库连接
        connection = configuration.getDataSource().getConnection();

        /** 2.获取preparedStatement预编译对象
            获取要执行的sql语句
                                        自定义的占位符
                   select * from user where id = #{id} and username = #{username}
            替换：  select * from user where id = ? and username = ?
                  解析替换的过程中：#{id}里面的值保存下来
         */
        BoundSql boundSql = getBoundSql(mappedStatement.getSql());
        // 获取预执行语句
        preparedStatement = connection.prepareStatement(boundSql.getSql());
        // 通过反射设置sql参数
        List<ParameterMapping> parameterList = boundSql.getParameterMappingList();
        for (int i = 0; i < parameterList.size(); i++) {
            Class<?> paramClass = Class.forName(mappedStatement.getParameterType());
            ParameterMapping parameterMapping = parameterList.get(i);
            String fieldName = parameterMapping.getContent();

            Field field = paramClass.getDeclaredField(fieldName);
            field.setAccessible(true); // 暴力访问
            Object value = field.get(param);
            // 设置字段参数
            preparedStatement.setObject(i + 1, value);
        }

        resultSet = preparedStatement.executeQuery();
        ResultSetMetaData metaData = resultSet.getMetaData();
        List<T> list = new ArrayList<>();
        // 加载映射结果class
        while (resultSet.next()) {
            Class<?> resultTypeClass = Class.forName(mappedStatement.getResultType());
            Object obj = resultTypeClass.newInstance();
            // 通过反射，一一封装所有字段
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                String columnName = metaData.getColumnName(i);
                Object value = resultSet.getObject(i);
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);
                Method method = propertyDescriptor.getWriteMethod();
                method.invoke(obj, value);
            }
            list.add((T) obj);
        }

        return list;
    }

    /**
     * 1.#{}占位符替换成？  2.解析替换的过程中 将#{}里面的值保存下来
     * @param sql select * from user where id = #{id} and username = #{username}
     * @return
     */
    private BoundSql getBoundSql(String sql) {
        // 1.创建标记处理器：配合标记解析器完成标记的处理解析工作
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        // 2.创建标记解析器
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);

        // #{}占位符替换成？ 2.解析替换的过程中 将#{}里面的值保存下来 ParameterMapping
        String finalSql = genericTokenParser.parse(sql);

        // #{}里面的值的一个集合 id username
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();

        BoundSql boundSql = new BoundSql(finalSql, parameterMappings);
        return boundSql;
    }

    // 释放资源
    @Override
    public void close() {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (preparedStatement != null) {
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }


}
